/**
 * 发布/编辑 文章路由
 */

var router = require('express').Router();
var userTool = require('../bin/user');
var articleTool = require('../bin/article');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var assertAlljs = require('../bin/util/assert-alljs');
var htmlcheck = require('../bin/htmlcheck');
var imagemeta = require('../bin/imagemeta');
var datetimeTool = require('../bin/util/datetime');
var blockTool = require('../bin/block');

router.post('/articlecommit', async function(req, res) {
    res.locals.descendantBlocks = blockTool.getDescendantBlocks(res.locals.blocks, res.locals.block);
    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);
    res.locals.edit = req.headers.referer.lastIndexOf('articledit') > -1;
    res.locals.reproduce = req.headers.referer.lastIndexOf('articlereproduce') > -1;
    let assert = assertAlljs(req, res, 'bodyRender:dyn.articledit.html');

    if (await assert(req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase(), '验证码错误!'))
        return;

    let user = req.session.user;

    // 检查是否登录
    let checkMessage = userTool.check(user);
    if (await assert(checkMessage))
        return;

    let {article, filter, error} = await articleTool.fromBody(req.body);
    if (await assert(error))
        return;

    if (await assert(htmlcheck.checkArticle(article.content)))
        return;

    if (await assert(htmlcheck.checkArticleBrief(article.brief)))
        return;

    // 查询是否重复发文(标题相同)
    let docs = await dbentityTool.find('article', filter);
    if (await assert(docs.length > 1 || (docs.length === 1 && docs[0]._id.toString() !== article._id), '提交文章失败，存在相同的文章标题'))
        return;

    if (typeof(req.body._id) === 'string' && req.body._id!==''){
        let oriArticle = await dbentityTool.findOne('article', {_id:ObjectID(req.body._id)});
        articleTool.copyDetails(article, user, oriArticle);
    }else {
        articleTool.newDetails(article, user);
    }

    article.content = article.content.replace(/\r\n\r\n/g, '\r\n');
    let articleContent = article.content;
    delete article.content;

    let articleId = await dbentityTool.upsert('article', article);
    if (await assert(articleId instanceof Error))
        return;
    if (await assert(typeof(articleId)!=='string', '保存文章到数据库异常'))
        return;

    article._id = articleId;

    req.behavior.set(articleId);

    // 保存文章html内容(因处理文章图片容易出错，所以先存一次)
    articleTool.saveContent(articleId, articleContent);
    articleTool.saveContentText(articleId, article.title, article.keywords, article.author, article.produceUser.nickname, articleContent);

    if (typeof(req.body._id) === 'string' && req.body._id!=='') {
        await req.session.pushMessage('文章保存成功, 并同时审核(最长半小时), 涉及非法内容者将被屏蔽');
        res.redirect('./article.html?id='+articleId);
    } else {
        await req.session.pushMessage('文章发布成功, 并同时审核(最长半小时), 涉及非法内容者将被屏蔽');
        res.redirect('./article.html?id='+articleId);
    }

    // 处理文章中的图片，对外部图片进行保存，过大图片进行压缩，并获取简要图片
    let {newhtml, briefImages, error2} = await imagemeta.handleContentImages(articleId, articleContent);
    if (await assert(error2))
        return;

    if (!('briefImages' in article) || JSON.stringify(briefImages) !== JSON.stringify(article.briefImages))
        await dbentityTool.findOneAndUpdate('article', {_id:ObjectID(articleId)}, {$set:{briefImages}});

    // 保存文章html内容(再次保存)
    articleContent = newhtml;
    articleTool.saveContent(articleId, articleContent);

    let audit = {
        produceUser: article.produceUser,
        produceTime: datetimeTool.to_yMdHms(article.modifyTime, '-', ' ', ':'),
        produceArticle: articleTool.getProfile(article),
        type: 'article',
        path: '',
        brief: article.brief
    };

    //提交给审核页面
    require('../appWS').io.to('publishaudit').emit('newitem', audit);
});

module.exports = router;